package com.lenovo.newsapp.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.adobe.mobile.Analytics;
import com.adobe.mobile.Config;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.LoginButton;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.lenovo.newsapp.R;
import com.lenovo.newsapp.model.CurrentColumnId;
import com.lenovo.newsapp.model.HomeNews;
import com.lenovo.newsapp.parser.InfoJSONParser;
import com.lenovo.newsapp.share.AsyncPostLoader;
import com.lenovo.newsapp.share.AsyncPostLoader.onPostReadyListener;
import com.lenovo.newsapp.util.Const;
import com.lenovo.newsapp.util.FileUtil;
import com.lenovo.newsapp.util.HttpUtil;
import com.lenovo.newsapp.util.PreferenceUtil;
import com.lenovo.newsapp.util.ThreadPool;
import com.lenovo.newsapp.util.Tools;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLProcedureInvocationData;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.WLResponseListener;

public class NewsDetailImgActivity extends BaseActivity implements
		OnClickListener {

	private static final String TAG = "NewsDetailImgActivity";

	private ViewPager viewPager;
	protected ArrayList<HomeNews> resultList;
	private ArrayList<View> views;
	private HomeNews detail;
	private ArrayList<CurrentColumnId> currentColumnIdList;
	protected int statusCode;
	private TextView titleTV;
//	private TextView contentTV;
	private TextView indexTV;
	private TextView allTV;
	private TextView keyword;
	private TextView author;
	private TextView updatetime;
	private TextView line;
	private WebView webview;
	// private ImageView btn_left;//图片右划
	// private ImageView btn_right;//图片左划
	private Dialog dialog;
	private Dialog share_dialog;
	private TextView shareCancelBtnTV;
	private TextView detailLikeBtnTV;
	private TextView detailCommentBtnTV;
	private TextView detailLikeNumTV;
	private TextView detailCommentNumTV;
	private LinearLayout likeAndCommentLL;

	// share
	private ImageView twitter;
	private ImageView facebook;
	private ImageView linkedIn;
	private ImageView instagram;
	private ImageView circle_of_friend;
	private ImageView wechat;
	private LoginButton facebookLoginButtton;
	
	private String newsid;
	private ScrollView sv;
	
	private Menu newMenu;
	// Facebook facebook = new Facebook("734563836621742");

	private IWXAPI api;

	protected String shortUrl;

	private RelativeLayout imgTextLayout;
	
	private UiLifecycleHelper uiHelper;
	
	private MainActivity main;
	
	final int RIGHT = 0;  
    final int LEFT = 1;  
    private GestureDetector gestureDetector; 
    
    private boolean imgIsScroll = false;//是否是滑动新闻中图片
    
    private String currentImgName;//当前图片name
    
    public static final String BROADCAST_AUTH_SUCCESS = "com.lenovo.broadcast.authsuccess";
//	private AuthSuccessBroadcastReceiver authSuccessBroadcastReceiver;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail_news_img);

		api = WXAPIFactory.createWXAPI(this, Const.WX_APP_ID);

		// 讲应用的appid注册到微信
		api.registerApp(Const.WX_APP_ID);

		HashMap<String, Object> map = MainActivity
				.getSection(Const.currentSection);
		String title = map.get("title").toString();
		actionBar.setTitle(title);
		newsid = getIntent().getStringExtra("id");
		Log.v(TAG, "newsid = "+newsid);
		// btn_left = (ImageView) findViewById(R.id.btn_left);
		// btn_right = (ImageView) findViewById(R.id.btn_right);
		sv = (ScrollView) findViewById(R.id.sv);
		
		loadData(Const.INIT_FLAG);
		
		uiHelper = new UiLifecycleHelper(this, callback);
		uiHelper.onCreate(savedInstanceState);
		
		gestureDetector = new GestureDetector(NewsDetailImgActivity.this,onGestureListener);  
		
		Analytics.trackState("NewsDetail Activity", null);//activity的名称 News，Video...
		
//		Log.v(TAG, "Environment="+Environment.getExternalStorageDirectory()
//				.getPath());
	}

	//
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Log.v(TAG, "detail onCreateOptionsMenu...");
		getMenuInflater().inflate(R.menu.detail_menu, menu);
		
		newMenu = menu;
		
		if(null != detail && detail.getCollect() == 1){
			if(null != newMenu){
				newMenu.getItem(1).setIcon(R.drawable.favorite_a);
			}
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_refresh) {
			// 刷新
			try {
				loadData(Const.REFRESH_FLAG);
				Const.manuallyRefresh = true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			sv.pageScroll(View.FOCUS_UP);
			return true;
		} else if (id == android.R.id.home) {
				Const.isFrefresh=false;
			finishWithAnimation();
			return true;
		}

		else if (id == R.id.action_favorite) {
			// 收藏
			Log.v(TAG, "点击 收藏");
			if(detail.getCollect() == 1){
				deletFavorite();
			}else{
				addFavorite();
			}
		} else if (id == R.id.action_share) {
			// 分享
			// popUpWindowMore.dismiss();
			dialog = new Dialog(NewsDetailImgActivity.this,
					R.style.MyShareDialog);
			dialog.setContentView(R.layout.share_layout);
			Window dialogWindow = dialog.getWindow();
			dialogWindow.setGravity(Gravity.BOTTOM);

			dialog.show();
			dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT);

			twitter = (ImageView) dialog.getWindow().findViewById(
					R.id.share_twitter);
			facebook = (ImageView) dialog.getWindow().findViewById(
					R.id.share_facebook);
			linkedIn = (ImageView) dialog.getWindow().findViewById(
					R.id.share_linkediIn);
			instagram = (ImageView) dialog.getWindow().findViewById(
					R.id.share_instagram);
			circle_of_friend = (ImageView) dialog.getWindow().findViewById(
					R.id.share_circle_of_friends);
			wechat = (ImageView) dialog.getWindow().findViewById(
					R.id.share_wechat);
			shareCancelBtnTV = (TextView) dialog.getWindow().findViewById(
					R.id.share_cancel_btn_tv);
			
			facebookLoginButtton = (LoginButton) findViewById(R.id.facebook_login_button);

			twitter.setOnClickListener(this);
			facebook.setOnClickListener(this);
			linkedIn.setOnClickListener(this);
			instagram.setOnClickListener(this);
			circle_of_friend.setOnClickListener(this);
			wechat.setOnClickListener(this);
			shareCancelBtnTV.setOnClickListener(this);

		}
		return super.onOptionsItemSelected(item);
	}

	private void loadData(final int flag) {
		showLoadProgressBar();
		ThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				try {
					// String s = InfoJSONParser.getGalleriesNewDetail().
					detail = InfoJSONParser.getGalleriesNewDetail(newsid, NewsDetailImgActivity.this,flag);
					success = true;
				} catch (Exception e) {
					success = false;
					e.printStackTrace();
				}

				handler.post(new Runnable() {

					@Override
					public void run() {
						if (success) {
							setUpViews();
						} else {
							showShortToast(R.string.toast_err_download);
						}

						hideLoadProgressBar();
					}

				});
			}
		});
	}

	private void setUpViews() {
		viewPager = (ViewPager) findViewById(R.id.viewpager);
//		contentTV = (TextView) findViewById(R.id.content);
		titleTV = (TextView) findViewById(R.id.title);
		indexTV = (TextView) findViewById(R.id.index);
		allTV = (TextView) findViewById(R.id.all);
		webview = (WebView) findViewById(R.id.webview);
		imgTextLayout = (RelativeLayout) findViewById(R.id.imgtext);

		keyword = (TextView) findViewById(R.id.tv_keyword);
		author = (TextView) findViewById(R.id.tv_author);
		updatetime = (TextView) findViewById(R.id.tv_last_update_time);
		
		detailLikeBtnTV = (TextView) findViewById(R.id.news_detail_like_btn_tv);
		detailLikeBtnTV.setOnClickListener(this);
		detailCommentBtnTV = (TextView) findViewById(R.id.news_detail_comment_btn_tv);
		detailCommentBtnTV.setOnClickListener(this);
		detailLikeNumTV = (TextView) findViewById(R.id.news_detail_like_num_tv);
		detailCommentNumTV = (TextView) findViewById(R.id.news_detail_comment_num_tv);
		likeAndCommentLL = (LinearLayout) findViewById(R.id.like_and_comment_ll);
		if(Const.currentSection != 5){
			likeAndCommentLL.setVisibility(View.VISIBLE);
		}
		

		line = (TextView) findViewById(R.id.line);
		if (detail == null)
			return;
		views = new ArrayList<View>();

		LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 200);

		line.setBackgroundColor(Color.BLACK);
		// btn_left.setVisibility(View.VISIBLE);
		// btn_right.setVisibility(View.VISIBLE);
		titleTV.setText(detail.getTitle());
//		CharSequence charSequence = Html.fromHtml(detail.getContent()); 
//		contentTV.setText(charSequence);
		
		String content = "<html><body>"
				+ detail.getContent()
				+ "</html></body>";
		webview.loadDataWithBaseURL(null, content,
				"text/html", "utf-8", null);
		WebSettings webSettings = webview.getSettings(); // webView:
															// 类WebView的实例
		webSettings
				.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); // 就是这句
		webSettings.setUseWideViewPort(false);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setSupportZoom(false);

		webSettings
				.setTextSize(WebSettings.TextSize.NORMAL);
//		contentTV.setText("" + Html.fromHtml(detail.getContent()));
		updatetime.setText(detail.getLastUpdateTime());
		keyword.setText(detail.getKeyword());
		author.setText("   |   " + detail.getAuthor());
		if (detail.getImageDetailList() != null) {

			if (detail.getImageDetailList().size() > 0) {
				imgTextLayout.setVisibility(View.VISIBLE);
				viewPager.setVisibility(View.VISIBLE);
				indexTV.setText("1");
				allTV.setText("/" + detail.getImageDetailList().size());
				
				final String[] imgName = new String[detail.getImageDetailList().size()];//新闻详情中图片名称

				Log.v(TAG, "detail.getImageDetailList() = "+detail.getImageDetailList());
				// 初始化引导图片列表
				for (int i = 0; i < detail.getImageDetailList().size(); i++) {
					ImageView iv = new ImageView(this);
					iv.setLayoutParams(mParams);
					final String url = Const.DOMAIN
							+ detail.getImageDetailList().get(i).getUrl();
					Tools.setImg(url, iv, this);
					String filename = url.substring(url.lastIndexOf("/") + 1);
					Log.v(TAG, "filename = " + filename);
					imgName[i]=filename;
					views.add(iv);
				}
				currentImgName = imgName[0];
				Log.v(TAG, "imgName.length="+imgName.length);

				imgAdapter adapter = new imgAdapter();
				viewPager.setAdapter(adapter);
				viewPager.setOnPageChangeListener(new OnPageChangeListener() {

					@Override
					public void onPageSelected(int position) {
						Log.v(TAG, "图片滑动 position = " +position);
						currentImgName = imgName[position];
						int index = position + 1;
						indexTV.setText("" + index);
					}

					@Override
					public void onPageScrolled(int arg0, float arg1, int arg2) {
						// TODO Auto-generated method stub
						Log.v(TAG, "图片滑动 - onPageScrolled");
					}

					@Override
					public void onPageScrollStateChanged(int arg0) {
						// TODO Auto-generated method stub
						if(arg0 == 1){
							imgIsScroll = true;
						}else if(arg0 == 0){
							imgIsScroll = false;
						}
						Log.v(TAG, "图片滑动 - onPageScrollStateChanged"+arg0);
					}
				});
			} else {
				imgTextLayout.setVisibility(View.GONE);
				viewPager.setVisibility(View.GONE);
			}
		} else {
			imgTextLayout.setVisibility(View.GONE);
			viewPager.setVisibility(View.GONE);
		}
		
		if(detail.getCollect() == 1){
			if(null != newMenu){
				newMenu.getItem(1).setIcon(R.drawable.favorite_a);
			}
		}
		if(detail.getLike() == 1){
			detailLikeBtnTV.setBackgroundResource(R.drawable.btn_praise_a);
		}
		detailLikeNumTV.setText(detail.getLikeCount()+"");
		detailCommentNumTV.setText(detail.getCommentCount()+"");
		
		loadCurrentColumnIdList();
	}

	private class imgAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return views.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View v = views.get(position);
			container.addView(v);
			return v;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {

			if(position < views.size()){
				View v = views.get(position);
				container.removeView(v);
			}

		}
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.share_twitter:
			getShortUrl(detail.getNewsId(), id);
			dialog.dismiss();
			break;
		case R.id.share_facebook:
			/**
			 * 分享时必须先拿到 facebook 的授权 token。 这里分两种情况，一是你安装了
			 * facebook的客户端，这时最简单直接调起你的facebook客户端授权分享
			 * 没有安装客户端时会调用网页授权，需要你输入自己的用户名和密码
			 */
			if (FacebookDialog.canPresentShareDialog(getApplicationContext(),
					FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
				// 已安装 facebook android 客户端
				// Publish the post using the Share Dialog
				FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(NewsDetailImgActivity.this).setLink(
						"https://developers.facebook.com/android").build();
				uiHelper.trackPendingDialogCall(shareDialog.present());
			} else {
				// 未安装 facebook android 客户端
				Session session = Session.getActiveSession();
				if (session == null) {
					// 未授权过
					Toast.makeText(NewsDetailImgActivity.this, "未安装 facebook 客户端，请先登录授权", Toast.LENGTH_LONG).show();
					facebookLoginButtton.setVisibility(View.VISIBLE);
				} else if (session.isOpened()) {
					// 已授权过 ，session 存在且打开
					// 调起网页分享
					Log.v("ddd", "调起网页分享");
					publishFeedDialog();
				} else {
					// session 存在但已关闭
					Session.openActiveSession(NewsDetailImgActivity.this, true, callback);
				}
			}
			dialog.dismiss();
//			Toast.makeText(NewsDetailImgActivity.this, R.string.not_been_enabled, Toast.LENGTH_LONG).show();
			break;
		case R.id.share_linkediIn:
			getShortUrl(detail.getNewsId(), id);
//			createLinkedinIntent();
//			shareToLinkedin();
//			Toast.makeText(NewsDetailImgActivity.this, R.string.not_been_enabled, Toast.LENGTH_LONG).show();
			dialog.dismiss();
			break;
		case R.id.share_instagram:
			FileUtil fileUtil = new FileUtil(this);
			String type = "image/*";
			String filename = currentImgName;
			String mediaPath = fileUtil.getAbsolutePath() + "/" + filename;
//			String mediaPath = Environment.getExternalStorageDirectory() + filename;
			String captionText = "<< media caption >>";

			Log.v(TAG, "mediaPath = " + mediaPath);
			createInstagramIntent(type, mediaPath, captionText);
//			Toast.makeText(NewsDetailImgActivity.this, R.string.not_been_enabled, Toast.LENGTH_LONG).show();
			dialog.dismiss();
			break;
		case R.id.share_circle_of_friends:
		case R.id.share_wechat:
			// getShortUrl(detail.getNewsId(), id);
			WXWebpageObject webpage = new WXWebpageObject();
//			webpage.webpageUrl = Const.SHARE_URL + 222;
			 webpage.webpageUrl = Const.SHARE_URL + detail.getNewsId();
			WXMediaMessage msg = new WXMediaMessage(webpage);
			msg.title = detail.getTitle();

			SendMessageToWX.Req req = new SendMessageToWX.Req();
			req.transaction = buildTransaction("webpage");
			req.message = msg;
			if (id == R.id.share_circle_of_friends) {
				req.scene = SendMessageToWX.Req.WXSceneTimeline;
			} else {
				req.scene = SendMessageToWX.Req.WXSceneSession;
			}
			api.sendReq(req);
			dialog.dismiss();
			break;
		case R.id.share_cancel_btn_tv:
			dialog.dismiss();
			break;
		case R.id.news_detail_like_btn_tv:
			if(detail.getLike() == 0){
				addLike(Const.LIKE);
			}else{
				Toast.makeText(NewsDetailImgActivity.this, R.string.already_like,Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.news_detail_comment_btn_tv:
			Intent intent = new Intent();
			intent.setClass(NewsDetailImgActivity.this,
					CommentActivity.class);
			intent.putExtra("newsId", detail.getNewsId());
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	/**
	 * 获取短链接并分享
	 * 
	 * @param newsId
	 *            当前新闻id
	 * @param id
	 *            点击分享类型的id（微信、朋友圈、twitter。。。）
	 */
	public void getShortUrl(int newsId, final int id) {
//		final String url = Const.TINY_URL + Const.SHARE_URL + 222;
		 final String url = Const.TINY_URL+Const.SHARE_URL+newsId;

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					shortUrl = HttpUtil.getReturnStrFromUrl(HttpUtil.DO_GET,
							url, null, false);
					Log.v(TAG, shortUrl);
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.post(new Runnable() {
					@Override
					public void run() {
						if (id == R.id.share_twitter) {
							Intent intent = new Intent(
									NewsDetailImgActivity.this,
									TwitterActivity.class);
							intent.putExtra("title", detail.getTitle());
							intent.putExtra("shareUrl", shortUrl);
							startActivity(intent);
							dialog.dismiss();

						}else{
							Intent share = new Intent(android.content.Intent.ACTION_SEND);
							share.setType("text/plain");
							String title = detail.getTitle();
							share.putExtra(Intent.EXTRA_TEXT, shortUrl);
							if (title != null) {
								share.putExtra(Intent.EXTRA_SUBJECT, title);
							}
							startActivity(Intent.createChooser(share, getString(R.string.select_linkedin)));
						}
					}
				});
			}
		}).start();
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	/**
	 * 添加收藏
	 */
	private void addFavorite() {
		Log.v(TAG,  "addFavorite...");
		showLoadProgressBar();
		String adapterName = "NewsAppAdapter";
		String procedureName = "collectNews";
		WLProcedureInvocationData invocationData = new WLProcedureInvocationData(
				adapterName, procedureName);
		Object[] parameters = new Object[] { PreferenceUtil.getString("username", ""), "" + detail.getNewsId() };
		invocationData.setParameters(parameters);
		

		LoginActivity.client = WLClient.getInstance();
		LoginActivity.client.invokeProcedure(invocationData,
				new WLResponseListener() {

					public void onSuccess(WLResponse response) {
						final JSONObject jsonObj = response.getResponseJSON();
						handler.post(new Runnable() {

							@Override
							public void run() {
								try {
//									showResult(jsonObj,"collect");
									if(detail.getCollect() == 0){
										newMenu.getItem(1).setIcon(R.drawable.favorite_a);
										if(jsonObj.getInt("status_code") == 0){
											detail.setCollect(1);
											loadData(Const.REFRESH_FLAG);
											Const.manuallyRefresh = true;
											Toast.makeText(NewsDetailImgActivity.this, R.string.collect_success,Toast.LENGTH_LONG).show();
										}else{
											Toast.makeText(NewsDetailImgActivity.this, R.string.collect_failure,Toast.LENGTH_LONG).show();
										}
									}
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								hideLoadProgressBar();

							}

						});

					}

					public void onFailure(WLFailResponse response) {
						String responseText = response.getResponseText();
						handler.post(new Runnable() {

							@Override
							public void run() {
								Toast.makeText(NewsDetailImgActivity.this, R.string.collect_failure,Toast.LENGTH_LONG).show();
								hideLoadProgressBar();
							}

						});
					}

				}, null);

	}
	
	/**
	 * 取消收藏
	 */
	private void deletFavorite() {
		showLoadProgressBar();
		String adapterName = "NewsAppAdapter";
		String procedureName = "collectDelete";
		WLProcedureInvocationData invocationData = new WLProcedureInvocationData(
				adapterName, procedureName);
		Object[] parameters = new Object[] { PreferenceUtil.getString("username", ""), "" + detail.getNewsId() };
		invocationData.setParameters(parameters);
		
		
		LoginActivity.client = WLClient.getInstance();
		LoginActivity.client.invokeProcedure(invocationData,
				new WLResponseListener() {
			
			public void onSuccess(WLResponse response) {
				final JSONObject jsonObj = response.getResponseJSON();
				handler.post(new Runnable() {
					
					@Override
					public void run() {
						try {
//							showResult(jsonObj,"collect");
							if(detail.getCollect() == 1){
								newMenu.getItem(1).setIcon(R.drawable.favorite);
								if(jsonObj.getInt("status_code") == 0){
									detail.setCollect(0);
									loadData(Const.REFRESH_FLAG);
									Const.manuallyRefresh = true;
									Toast.makeText(NewsDetailImgActivity.this, R.string.delete_collect_success,Toast.LENGTH_LONG).show();
								}else{
									Toast.makeText(NewsDetailImgActivity.this, R.string.delete_collect_failure,Toast.LENGTH_LONG).show();
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						hideLoadProgressBar();
						
					}
					
				});
				
			}
			
			public void onFailure(WLFailResponse response) {
				String responseText = response.getResponseText();
				handler.post(new Runnable() {
					
					@Override
					public void run() {
						Toast.makeText(NewsDetailImgActivity.this, R.string.delete_collect_failure,Toast.LENGTH_LONG).show();
						hideLoadProgressBar();
					}
					
				});
			}
			
		}, null);
		
	}

	/**
	 * 点赞
	 */
	private void addLike(String type) {
		showLoadProgressBar();
		String adapterName = "NewsAppAdapter";
		String procedureName = "likeNews";
		WLProcedureInvocationData invocationData = new WLProcedureInvocationData(
				adapterName, procedureName);
		Object[] parameters = new Object[] { PreferenceUtil.getString("username", ""), "" + detail.getNewsId(),
				type };
		invocationData.setParameters(parameters);

		LoginActivity.client = WLClient.getInstance();
		LoginActivity.client.invokeProcedure(invocationData,
				new WLResponseListener() {

					public void onSuccess(WLResponse response) {
						final JSONObject jsonObj = response.getResponseJSON();
						handler.post(new Runnable() {

							@Override
							public void run() {
								try {
//									showResult(jsonObj,"like");
									if(jsonObj.getInt("status_code") == 0){
										detailLikeBtnTV.setBackgroundResource(R.drawable.btn_praise_a);
										detail.setLike(1);
										loadData(Const.REFRESH_FLAG);
										Const.manuallyRefresh = true;
										Toast.makeText(NewsDetailImgActivity.this, R.string.like_success,Toast.LENGTH_LONG).show();
									}else{
										Toast.makeText(NewsDetailImgActivity.this, R.string.like_failure,Toast.LENGTH_LONG).show();
									}
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								hideLoadProgressBar();
							}

						});

					}

					public void onFailure(WLFailResponse response) {
						String responseText = response.getResponseText();
						handler.post(new Runnable() {

							@Override
							public void run() {
								hideLoadProgressBar();
							}

						});
					}

				}, null);

	}

//	protected void showResult(JSONObject jsonObj,String str) throws JSONException {
//		int code = jsonObj.getInt("status_code");
//		if (code == 0) {
//			if(str.equals("collect") && detail.getCollect() == 0){
//				newMenu.getItem(1).setIcon(R.drawable.favorite_a);
//				detail.setCollect(1);
//			}else if(str.equals("collect") && detail.getCollect() == 1){
//				newMenu.getItem(1).setIcon(R.drawable.favorite);
//				detail.setCollect(0);
//			}
//			if(str.equals("like") && detail.getLike() == 0){
//				newMenu.getItem(2).setIcon(R.drawable.btn_praise_a);
//				detail.setLike(1);
//			}else if(str.equals("like") && detail.getLike() == 1){
//				newMenu.getItem(2).setIcon(R.drawable.btn_praise);
//				detail.setLike(0);
//			}
//			showShortToast(getResources().getString(R.string.toast_success));
//		} else {
//			showShortToast(getResources().getString(R.string.toast_err));
//		}
//
//	}
	
	/*------ Facebook start --------*/
	/**
	 * 与 facebook 会话监听
	 */
	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {

			if (exception instanceof FacebookOperationCanceledException
					|| exception instanceof FacebookAuthorizationException) {
				new AlertDialog.Builder(NewsDetailImgActivity.this).setTitle("提示").setMessage("授权失败")
						.setPositiveButton("Ok", null).show();
			} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
				new AlertDialog.Builder(NewsDetailImgActivity.this).setTitle("提示").setMessage("授权成功").show();
				// 授权成功后调起网页分享
				publishFeedDialog();
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
			@Override
			public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
				Log.e("Activity", String.format("Error: %s", error.toString()));
			}

			@Override
			public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
				Log.i("Activity", "Success!");
			}
		});
	}

	private void publishFeedDialog() {
		
//		String url = Const.SHARE_URL + 222;
		String url = Const.SHARE_URL + detail.getNewsId();
		String newUrl="";
		try {
			newUrl = HttpUtil.getReturnStrFromUrl(HttpUtil.DO_GET,
					url, null, false);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Bundle params = new Bundle();
		params.putString("name", "");
		params.putString("caption", detail.getTitle());
		params.putString("description","");
		params.putString("link", newUrl);
//		params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");

		WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(NewsDetailImgActivity.this, Session.getActiveSession(), params))
				.setOnCompleteListener(new OnCompleteListener() {

					@Override
					public void onComplete(Bundle values, FacebookException error) {
						if (error == null) {
							// When the story is posted, echo the success
							// and the post Id.
							final String postId = values.getString("post_id");
							if (postId != null) {
								Toast.makeText(NewsDetailImgActivity.this, "Posted story, id: " + postId, Toast.LENGTH_SHORT)
										.show();
							} else {
								// User clicked the Cancel button
								Toast.makeText(NewsDetailImgActivity.this.getApplicationContext(), "Publish cancelled",
										Toast.LENGTH_SHORT).show();
							}
						} else if (error instanceof FacebookOperationCanceledException) {
							// User clicked the "x" button
							Toast.makeText(NewsDetailImgActivity.this.getApplicationContext(), "Publish cancelled",
									Toast.LENGTH_SHORT).show();
						} else {
							// Generic, ex: network error
							Toast.makeText(NewsDetailImgActivity.this.getApplicationContext(), "Error posting story",
									Toast.LENGTH_SHORT).show();
						}
					}

				}).build();
		feedDialog.show();
	}

	@Override
	protected void onResume() {
		super.onResume();
		uiHelper.onResume();
		Config.collectLifecycleData();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
		Config.pauseCollectingLifecycleData();
	}

//	@Override
//	public void onDestroy() {
//		super.onDestroy();
//		if (authSuccessBroadcastReceiver != null) {
//			unregisterReceiver(authSuccessBroadcastReceiver);
//			authSuccessBroadcastReceiver = null;
//		}
//		uiHelper.onDestroy();
//	}
	/*------ Facebook end --------*/
	
	private GestureDetector.OnGestureListener onGestureListener = new GestureDetector.SimpleOnGestureListener() {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			Log.v(TAG, "onFling...");
			float x = e2.getX() - e1.getX();
			float y = e2.getY() - e1.getY();
			if (!imgIsScroll && x > 300) {
				doResult(RIGHT);
			} else if (!imgIsScroll && x < -300) {
				doResult(LEFT);
			}
			return true;
		}
	};

	public boolean onTouchEvent(MotionEvent event) {
		return gestureDetector.onTouchEvent(event);
	}

	public void doResult(int action) {
		

		switch (action) {
		case RIGHT:
			Log.v(TAG, "go right");
			for(int i=0;i<currentColumnIdList.size();i++){
				int id = currentColumnIdList.get(i).getNewsId();
				if(newsid.equals(id+"")){
					if(i == 0){
						Toast.makeText(NewsDetailImgActivity.this.getApplicationContext(), R.string.is_the_first,
								Toast.LENGTH_SHORT).show();
					}else{
						newsid = currentColumnIdList.get(i-1).getNewsId()+"";
						loadData(Const.INIT_FLAG);
					}
					break;
				}
			}
			break;

		case LEFT:
			Log.v(TAG, "go LEFT");
			for(int i=0;i<currentColumnIdList.size();i++){
				int id = currentColumnIdList.get(i).getNewsId();
				if(newsid.equals(id+"")){
					if(i == (currentColumnIdList.size()-1)){
						Toast.makeText(NewsDetailImgActivity.this.getApplicationContext(), R.string.is_the_last,
								Toast.LENGTH_SHORT).show();
					}else{
						newsid = currentColumnIdList.get(i+1).getNewsId()+"";
						loadData(Const.INIT_FLAG);
						
					}
					break;
				}
			}
			
			break;

		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODOAuto-generatedmethodstub
		gestureDetector.onTouchEvent(ev); // 让GestureDetector响应触碰事件
		super.dispatchTouchEvent(ev); // 让Activity响应触碰事件
		return false;
	}
	
	/**
	 * 加载当前栏目id list
	 */
	private void loadCurrentColumnIdList(){
		Log.v(TAG, "loadCurrentColumnIdList...");
		showLoadProgressBar();
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					// String s = InfoJSONParser.getGalleriesNewDetail().
					currentColumnIdList = InfoJSONParser.getCurrentColumnIdList();
					success = true;
				} catch (Exception e) {
					success = false;
					e.printStackTrace();
				}

				handler.post(new Runnable() {

					@Override
					public void run() {
						if (success) {
							
						} else {
							showShortToast(R.string.toast_err_download);
						}

						hideLoadProgressBar();
					}

				});
			}
		}).start();
	}
	
	/**
	 * 分享到Instagram
	 * @param type
	 * @param mediaPath
	 * @param caption
	 */
	private void createInstagramIntent(String type, String mediaPath, String caption){

	    // Create the new Intent using the 'Send' action.
	    Intent share = new Intent(Intent.ACTION_SEND);

	    // Set the MIME type
	    share.setType(type);

	    // Create the URI from the media
	    File media = new File(mediaPath);
	    Uri uri = Uri.fromFile(media);

	    // Add the URI and the caption to the Intent.
	    share.putExtra(Intent.EXTRA_STREAM, uri);
	    share.putExtra(Intent.EXTRA_TEXT, caption);

	    // Broadcast the Intent.
//	    startActivity(Intent.createChooser(share, "Share to"));
	    startActivity(Intent.createChooser(share, getString(R.string.select_instagram)));
	}
	
	private void createLinkedinIntent(){
		final Intent share = new Intent(android.content.Intent.ACTION_SEND);
		
		final String url = Const.SHARE_URL + detail.getNewsId();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					shortUrl = HttpUtil.getReturnStrFromUrl(HttpUtil.DO_GET,
							url, null, false);
					Log.v(TAG, shortUrl);
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.post(new Runnable() {
					@Override
					public void run() {
						share.setType("text/plain");
						String title = detail.getTitle();
						share.putExtra(Intent.EXTRA_TEXT, shortUrl);
						if (title != null) {
							share.putExtra(Intent.EXTRA_SUBJECT, title);
						}
						startActivity(Intent.createChooser(share, getString(R.string.select_linkedin)));
						
					}
				});
			}
		}).start();
		
		
	}
	
	/**
	 * 分享到 linkedin
	 * 
	 * @param shareContent
	 *            分享内容
	 * @param accessToken
	 */
//	private void shareToLinkedin(Map<String, String> shareContent, String accessToken) {
//		Log.v(TAG, "shareToLinkedin...");
//		String postUrl = "https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=" + accessToken;
//
//		try {
//			Log.v(TAG, "shareToLinkedin try...");
//			String title = shareContent.get("title"); // 标题
//			String comment = shareContent.get("comment"); // 评论
//			String description = shareContent.get("description"); // 描述
//			String submittedUrl = shareContent.get("submitted-url"); // 链接
//			// 图片 url
//			String imageUrl = shareContent.get("submitted-image-url");
//
//			// 以 XML 格式拼接要分享的内容
//			String xml = "<share>" + "<comment>" + comment + "</comment>" + "<content>" + "<title>" + title
//					+ "</title>" + " <description>" + description + "</description>" + "<submitted-url>" + submittedUrl
//					+ "</submitted-url>" + "<submitted-image-url>" + imageUrl + "</submitted-image-url>" + "</content>"
//					+ "<visibility>" + " <code>anyone</code>" + "</visibility>" + "</share>";
//
//			AsyncPostLoader post = new AsyncPostLoader(new onPostReadyListener() {
//
//				@Override
//				public void onPostReady(String result) {
//					if (result != null) {
//						Log.d("leslie", "result " + result);
//						Log.d("leslie", "分享成功 ");
//						Toast.makeText(NewsDetailImgActivity.this, "分享成功", Toast.LENGTH_LONG).show();
//					} else {
//						Log.d("leslie", "分享失败 ");
//						Toast.makeText(NewsDetailImgActivity.this, "分享失败", Toast.LENGTH_LONG).show();
//					}
//				}
//			});
//			Log.v(TAG, "shareToLinkedin xml ..." +xml);
//			post.execute(postUrl, xml);
//		} catch (Exception e) {
//			Log.v(TAG, "异常..." + e);
//		}
//	}

	/**
	 * 授权成功广播接收者
	 */
//	class AuthSuccessBroadcastReceiver extends BroadcastReceiver {
//
//		@Override
//		public void onReceive(Context context, Intent intent) {
//			if (intent.getAction().equals(BROADCAST_AUTH_SUCCESS)) {
//				// 授权成功后继续分享
//				Toast.makeText(NewsDetailImgActivity.this, "授权成功", Toast.LENGTH_LONG).show();
//			}
//		}
//	}
	
//	private void shareToLinkedin(){
//		SharedPreferences preferences = getSharedPreferences("user_info", 0);
//		String accessToken = preferences.getString("accessToken", null);
//		
//		Log.v(TAG, "linkedin accessToken = " + accessToken);
//
//		if (accessToken != null) {
//			Log.v(TAG, "linkedin accessToken != null");
//			// 已授权过 accessToken 存在
//			Map<String, String> shareContent = new HashMap<String, String>();
//			
//			String url = Const.SHARE_URL + detail.getNewsId();
//			
////			shareContent.put("title", "hello title");
////			shareContent.put("comment", "this is comment");
////			shareContent.put("description", "this is description");
////			shareContent.put("submitted-url", "http://www.baidu.com");
////			shareContent.put("submitted-image-url",
////					"http://www.baidu.com/img/baidu_jgylogo3.gif?v=22596777.gif");
//			
//			shareContent.put("title", detail.getTitle());
//			shareContent.put("comment", "");
//			shareContent.put("description", "");
//			shareContent.put("submitted-url", url);
//			shareContent.put("submitted-image-url","http://www.baidu.com/img/baidu_jgylogo3.gif?v=22596777.gif");
//
//			shareToLinkedin(shareContent, accessToken);
//		} else {
//			// 未授权过，调起授权界面进行授权
//			Intent intent = new Intent(NewsDetailImgActivity.this, LinkedinAuthActivity.class);
//			startActivity(intent);
//		}
//	}
}
